package pers.qianyu.module.core.util;

import cn.hutool.core.util.*;
import cn.hutool.http.*;
import cn.hutool.json.*;

/**
 * @author mizzle rain
 * @date 2020-11-03 12:11
 */
public class IpUtil {
    public static final String URL = "http://whois.pconline.com.cn/ipJson.jsp?ip=%s&json=true";

    /**
     * 根据 ip 地址获取位置信息
     *
     * @param ip ip地址
     * @return 信息字符串
     */
    public static String getInfoFromIp(String ip) {
        String url = String.format(URL, ip);
        HttpResponse response = HttpUtil.createGet(url).execute();
        if (response.isOk()) {
            String text = response.body();
            if (JSONUtil.isJson(text)) {
                JSONObject obj = JSONUtil.parseObj(text);
                String province = obj.getStr("pro");
                String city = obj.getStr("city");
                String region = obj.getStr("region");
                String addr = obj.getStr("addr");
                return String.format("地址：%s%s%s 运营商：%s", province, city, region, addr);
            }
        }
        return StrUtil.EMPTY;
    }
}
